<template>
  <div class="page-content" v-loading="loading">
    <div class="header">
      <h3>下单设置</h3>
    </div>
    <el-form label-width="120px" style="margin-top: 20px">
      <el-form-item label="开启订单审核：" class="bt0">
        <el-switch
          v-model="isautosh"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('isautosh', $event)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-tag
          >功能描述：功能开启后，客户在线上商铺提交的订单会自动审核转为报价单。【开启后立即生效】;</el-tag
        >
      </el-form-item>
      <el-form-item label="开启微信通知：" class="bt0">
        <el-switch
          v-model="istzcharge"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('istzcharge', $event)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-tag
          >功能描述：功能开启后，客户在线上商铺提交订单时推送的微信通知仅推送该客户的负责人，如果负责人没有则通知跟单员。【开启后立即生效】;</el-tag
        >
      </el-form-item>
      <el-form-item label="开启信用积分：" class="bt0">
        <el-switch
          v-model="isxyfen"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('isxyfen', $event)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-tag
          >功能描述：功能开启后，客户在线上商铺下单时受到信用积分限制，信用积分为零的客户无法下单。【开启后立即生效】;</el-tag
        >
      </el-form-item>
      <el-form-item label="开启图片水印：" class="bt0">
        <el-switch
          v-model="ispicsy"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('ispicsy', $event)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-tag
          >功能描述：功能开启后，客户在线上商铺看到的图片都会带有上传时图片设置的水印，默认开启。【开启后立即生效】;</el-tag
        >
      </el-form-item>
      <el-form-item label="关闭零库存和显示图片按钮：" class="bt0">
        <el-switch
          v-model="isshowbtn"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('isshowbtn', $event)"
        >
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-tag
          >功能描述：功能开启后，客户在线上下单的时候不显示零库存和显示图片的按钮，并默认显示图片和显示全部库存数据，默认关闭。【开启后立即生效】;</el-tag
        >
      </el-form-item>
      <el-form-item label="开启秒杀：">
        <el-switch
          v-model="isflashsale"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('isflashsale', $event)"
        >
        </el-switch>
        <el-date-picker
          v-model="datedata"
          type="datetime"
          placeholder="请选择截止日期"
        >
        </el-date-picker>
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="updateData('flashsaletime', '')"
          >保存日期</el-button
        >
      </el-form-item>
      <el-form-item label="下单时间：">
        <el-switch
          v-model="isonlinetime"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="updateData('isonlinetime', $event)"
        >
        </el-switch>
        <el-time-picker
          is-range
          arrow-control
          v-model="onlinetime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
        >
        </el-time-picker>
        <el-button type="primary" icon="el-icon-check" @click="uonlineTime"
          >保存时间</el-button
        >
      </el-form-item>
      <el-form-item label="下单公告：">
        <quill-editor
          class="editor"
          ref="quillEditor"
          v-model="settingform.body"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @ready="onEditorReady($event)"
        />
        <el-upload
          class="upload-demo"
          :action="dataUrl"
          :data="uploadData"
          :headers="headers"
          :on-success="upScuccess"
          ref="upload"
          multiple
          style="display:none"
        >
          <el-button
            type="primary"
            id="imgInput"
            v-loading.fullscreen.lock="fullscreenLoading"
            element-loading-text="插入中,请稍候"
          >
            点击上传
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="挂账协议：">
        <quill-editor
          class="editor"
          ref="quillEditor"
          v-model="settingform.protocol"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @ready="onEditorReady($event)"
        />
        <el-upload
          class="upload-demo"
          :action="dataUrl"
          :data="uploadData"
          :headers="headers"
          :on-success="upScuccess"
          ref="upload"
          multiple
          style="display:none"
        >
          <el-button
            type="primary"
            id="imgInput"
            v-loading.fullscreen.lock="fullscreenLoading"
            element-loading-text="插入中,请稍候"
          >
            点击上传
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" @click="saveData"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { quillEditor, Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "@styles/quill.scss";
import { baseUrl } from "@/utils/config";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import ImageResize from "quill-image-resize-module";
import { orderConfigurationApi } from "@/api/cardApi";
import { save_DataApi } from "@/api/cardApi";
import { orderManagerApi } from "@/api/cardApi";
import { orderOnlineTimeApi } from "@/api/cardApi";
import moment from "moment";

Quill.register("modules/ImageExtend", ImageExtend);
Quill.register("modules/ImageResize", ImageResize);

export default {
  inject: ["reload"],
  components: {
    quillEditor
  },
  data() {
    return {
      loading: true,
      uploadData: {
        guestcode: "",
        gscode: ""
      },
      headers: {
        Authorization: ""
      },
      isautosh: false,
      istzcharge: false,
      isxyfen: false,
      ispicsy: false,
      isflashsale: false,
      isonlinetime: false,
      isshowbtn: false,
      settingform: {
        body: "",
        protocol: ""
      },
      onlinetime: [new Date(2016, 9, 10, 8), new Date(2016, 9, 10, 20)],
      datedata: "",
      fullscreenLoading: false,
      dataUrl: baseUrl + "/api/Card/upload_Imgurl",
      editorOption: {
        modules: {
          ImageResize: {
            //调整大小组件。
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
          ImageExtend: {
            // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
            loading: true, // 可选参数 是否显示上传进度和提示语
            placeholder: "",
            name: "img", // 图片参数名
            size: 500, // 可选参数 图片大小，单位为M，1M = 1024kb
            methods: "POST", // 可选参数 图片上传方式  默认为post
            accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon",
            action: this.dataUrl, // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
            // 则 return res.data.url
            response: res => {
              let imgurl = "http://img.inheart.cn";
              return imgurl + res.statusText;
            },
            headers: xhr => {
              xhr.setRequestHeader("contentType", "application/json");
            }, // 可选参数 设置请求头部
            sizeError: () => {}, // 图片超过大小的回调
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 上传失败触发的事件
            success: () => {}, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {} // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            // 如果不上传图片到服务器，此处不必配置
            container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
            handlers: {
              image: function() {
                // 劫持原来的图片点击按钮事件
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      }
    };
  },
  mounted() {
    this.SettingData();
  },
  methods: {
    SettingData() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      orderConfigurationApi({
        guestcode: guestcode,
        gscode: gscode,
        username: username,
        userid: userid,
        menuename: "SystemSetting",
        menucname: "下单设置",
        logintype: logintype,
        posttype: posttype,
        op_type: "查询"
      }).then(res => {
        this.loading = false;
        if ((res.code = "0")) {
          this.isautosh = res.list[0].value;
          this.istzcharge = res.list[1].value;
          this.isxyfen = res.list[2].value;
          this.isflashsale = res.list[3].value;
          this.ispicsy = res.list[4].value;
          this.isonlinetime = res.list[5].value;
          this.datedata = res.flashsaletime;
          if (this.onlinetime != "") {
            this.onlinetime = [
              new Date(
                2016,
                9,
                10,
                res.list[9].value.split(":")[0],
                res.list[9].value.split(":")[1]
              ),
              new Date(
                2016,
                9,
                10,
                res.list[10].value.split(":")[0],
                res.list[10].value.split(":")[1]
              )
            ];
          }
          this.settingform.body = res.notice;
          this.settingform.protocol = res.protocol;
        }
      });
    },
    upScuccess(e) {
      let path = e.statusText;
      let url = "http://img.inheart.cn" + path;
      let quill = this.$refs.quillEditor.quill;
      let selection = quill.getSelection();

      // 获取光标的位置
      let cursorIndex = selection ? selection.index : 0;
      // 插入图片到编辑器
      quill.insertEmbed(cursorIndex, "image", url);
      // 调整光标到最后
      quill.setSelection(cursorIndex + 1);
    },
    onEditorBlur(quill) {}, // 失去焦点事件
    onEditorFocus(quill) {}, // 获得焦点事件
    onEditorReady(quill) {}, // 内容改变事件
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 转码
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    saveData() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      save_DataApi({
        guestcode: guestcode,
        gscode: gscode,
        notification: this.settingform.body,
        protocol: this.settingform.protocol
      }).then(res => {
        if (res.code == "0") {
          this.loading = true;
          this.$message.success("修改成功");
        } else {
          this.$message.error(res.msg);
        }
        this.SettingData();
      });
    },
    updateData(val, status) {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      orderManagerApi({
        guestcode: guestcode,
        gscode: gscode,
        ywtype: val,
        state: status,
        flashsaletime: this.datedata
      }).then(res => {
        if (res.code == "0") {
          this.loading = true;
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
        this.SettingData();
      });
    },
    uonlineTime() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let online_stime = moment(this.onlinetime[0]).format("HH:mm");
      let online_etime = moment(this.onlinetime[1]).format("HH:mm");
      orderOnlineTimeApi({
        guestcode: guestcode,
        gscode: gscode,
        online_stime: online_stime,
        online_etime: online_etime
      }).then(res => {
        if (res.code == "0") {
          this.loading = true;
          this.$message.success("修改成功");
        } else {
          this.$message.error(res.msg);
        }
        this.SettingData();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;

    h3 {
      font-size: 17px;
      font-weight: 500;
    }
  }

  ::v-deep .el-form {
    .bt0 {
      margin-bottom: 0;
    }
  }
}
</style>
